<?php


use Phinx\Seed\AbstractSeed;
use Faker\Factory as FakerFactory;
use App\Library\Utils\Arr;

class ArticleTagSeeder extends AbstractSeed
{
    public function getDependencies(): array
    {
        return [
            'ArticleSeeder',
            'TagSeeder',
        ];
    }

    /**
     * Run Method.
     *
     * Write your database seeder using this method.
     *
     * More information on writing seeders is available here:
     * https://book.cakephp.org/phinx/0/en/seeding.html
     */
    public function run()
    {
        $faker = FakerFactory::create('zh_CN');

        $tags = $this->fetchAll('SELECT * FROM kg_tag');
        $articles = $this->fetchAll('SELECT * FROM kg_article');

        $rows = [];
        $rels = [];
        $loop = count($articles) * 2;
        for ($i = 0; $i < $loop; $i++) {
            $articleId = Arr::rand($articles)['id'];
            $tagId = Arr::rand($tags)['id'];
            $rels[$articleId][] = $tagId;
            $rows[] = [
                'article_id' => $articleId,
                'tag_id' => $tagId,
                'create_time' => $faker->unixTime,
            ];
        }

        $this->table('kg_article_tag')->insert($rows)->saveData();

        // 更新 article
        foreach ($rels as $aid => $tids) {
            $ids = implode($tids, ',');
            $tags = $this->fetchAll("SELECT * FROM kg_tag WHERE id IN (${ids})");
            $json = [];
            foreach ($tags as $tag) {
                $json[] = [
                    'id' => $tag['id'],
                    'name' => $tag['name'],
                ];
            }
            $json = json_encode($json, JSON_UNESCAPED_UNICODE);
            $this->execute("UPDATE kg_article SET tags='${json}' WHERE id=${aid}");
        }
    }

}
